﻿using System;
using System.Linq;
using System.Net.Sockets;
using Mozi.HttpEmbedded;
using Mozi.HttpEmbedded.Encode;
using Mozi.HttpEmbedded.Extension;
using Mozi.Live.RTP;
using Mozi.Live.RTSP;
using Mozi.Live.SDP;

namespace Mozi.Live
{

    //TODO 实现UDP传输信道
    //TODO 实现控制服务端的API
    //TODO Server/Client为对等模式

    //RTSP支持摘要认证，在HttpServer已实现摘要认证，故此处不需要单独实现

    /// <summary>
    /// RTSP2.0 服务器
    /// </summary>
    public class RTSPServer: HttpServer
    {
        private int _port = RTSPProtocol.Port;

        private string[] _features = { "play.basic", "play.scale", "play.speed", /*支持RTP|RTCP over RTSP*/"setup.rtp.rtcp.mux" };

        private RTSPTransportProtocol _transport = new RTSPTransportProtocol();

        private SessionManager _sm = new SessionManager();

        private RTPServer rtp = new RTPServer();

        private RTCPServer rtcp = new RTCPServer();
        /// <summary>
        /// 媒体缓冲层
        /// </summary>
        public MediaCache MediaLayer = new MediaCache();

        /// <summary>
        /// 会话对象
        /// </summary>
        public SessionManager Sessions
        {
            get
            {
                return _sm;
            }
        }
        /// <summary>
        /// 工作端口，默认为<see cref="RTSPProtocol.Port"/>
        /// </summary>
        public override int Port
        {
            get { return _port; } protected set {_port = value;}
        }
        /// <summary>
        /// RTP消息接收事件
        /// </summary>
        public RTPMessageTransmit RTPMessageReceived
        {
            get
            {
                return rtp.MessageReceived;
            }
            set
            {
                rtp.MessageReceived += value;
            }
        }
        /// <summary>
        /// RTP消息发送事件
        /// </summary>
        public RTPMessageTransmit RTPMessageSend
        {
            get
            {
                return rtp.MessageSend;
            }
            set
            {
                rtp.MessageSend += value;
            }
        }
        /// <summary>
        /// RTCP消息接收事件
        /// </summary>
        public RTCPMessageTransmit RTCPMessageReceived
        {
            get
            {
                 return rtcp.MessageReceived;
            }
            set
            {
                rtcp.MessageReceived+= value;
            }
        }
        /// <summary>
        /// RTCP消息发送事件
        /// </summary>
        public RTCPMessageTransmit RTCPMessagedSend
        {
            get
            {
                return rtcp.MessageSend;
            }
            set
            {
                rtcp.MessageSend += value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public RTSPServer()
        {
            Version = RTSPVersion.Version20;
            AutoCloseSession = false;
            //定义允许的方法
            MethodPublic = new RequestMethod[] { RTSPMethod.OPTIONS, RTSPMethod.DESCRIBE, RTSPMethod.PLAY, RTSPMethod.PAUSE, RTSPMethod.SETUP, RTSPMethod.TEARDOWN, RTSPMethod.GET_PARAMETER,RTSPMethod.ANNOUNCE,RTSPMethod.RECORD};
        }
        /// <summary>
        /// 启动RTP/UDP
        /// </summary>
        /// <param name="port"></param>
        public void StartRTP(int port)
        {
            rtp.Start(port);
            rtp.MessageReceived += (x, y, z) =>
            {
                //TODO channel 通道测算
                HandleMessageRTP(x,y,"UDP",0,z);
            };
            rtp.MessageSend += (x, y, z) =>
            {
                HandleMessageSendRTP(x, y, "UDP", 0, z);
            };
        }
        /// <summary>
        /// 启动RTCP/UDP
        /// </summary>
        /// <param name="port"></param>
        public void StartRTCP(int port)
        {
            rtcp.Start(port);
            rtcp.MessageReceived += (x, y, z) =>
            {
                //TODO channel 通道测算
                HandleMessageRTCP(x, y, "UDP", 0, z);
            };
            rtcp.MessageSend += (x, y, z) =>
            {
                HandleMessageSendRTCP(x, y, "UDP", 0, z);               
            };
        }
        /// <summary>
        /// 处理RTP数据
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="protocol"></param>
        /// <param name="channel"></param>
        /// <param name="pack"></param>
        private void HandleMessageRTP(string ip, int port, string protocol, byte channel, RTPPackage pack)
        {
            //TODO 这里需要测算出时间
            //Console.WriteLine($"RTP/{protocol} {ip}:{port}=>CH={channel} PT={pack.PayloadType} SSRC={pack.SSRC} SEQ={pack.SequenceNumber} T={pack.Timestamp} "+(pack.Marker?"MK":""));

            //TODO 如何测算出资源名称
            var resource = MediaLayer.First();
            resource.AddMedia(channel, pack);
            foreach (var s in _sm.GetSubscribers(resource.ResourceName))
            {
                s.Push(channel, pack);
            }
            resource.PopAll();
        }
        /// <summary>
        /// 处理RTCP数据
        /// </summary>
        private void HandleMessageRTCP(string ip, int port, string protocol, byte channel, AbsRTCPPackage pack)
        {
            Console.WriteLine($"RTCP/{protocol} {ip}:{port}=>CH={channel} PT={pack.PackageType.Name}");
        }
        /// <summary>
        /// 处理RTP发送事件
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="protocol"></param>
        /// <param name="channel"></param>
        /// <param name="pack"></param>
        public void HandleMessageSendRTP(string ip, int port, string protocol, byte channel, RTPPackage pack)
        {
            //Console.WriteLine($"RTP/{protocol} {ip}:{port}<=CH={channel} PT={pack.PayloadType} SSRC={pack.SSRC} SEQ={pack.SequenceNumber} T={pack.Timestamp}");
        }
        /// <summary>
        /// 处理RTCP发送事件
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="protocol"></param>
        /// <param name="channel"></param>
        /// <param name="pack"></param>
        public void HandleMessageSendRTCP(string ip, int port, string protocol, byte channel, AbsRTCPPackage pack)
        {
            Console.WriteLine($"RTCP/{protocol} {ip}:{port}<=PT={pack.PackageType.Name}");
        }
        /// <summary>
        /// 接管数据处理信道
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        protected override void Socket_AfterReceiveEnd(object sender, DataTransferArgs args)
        {
            //'$'起首标记为RTP数据
            if (args.Data.Length==0||args.Data[0] != 0x24)
            {
                base.Socket_AfterReceiveEnd(sender, args);
            }
            //解析复合数据包 RTP|RTCP 
            //这种数据包以'$'开头，即0x24开始
            else
            {
                int offset =0;
                while (args.Data[offset] == 0x24)
                {
                    //DONE 对包进行重组分片
                    if (offset+4>args.Data.Length)
                    {
                        break;
                    }
                    byte channel = args.Data[offset+1];
                    ushort length = args.Data.GetBigEndianUInt16(offset+2);
                    byte[] buffer = new byte[length];
                    if (args.Data.Length > offset + 4 + length)
                    {
                        Array.Copy(args.Data, offset + 4, buffer, 0, length);
                        try
                        {
                            var session = _sm.FindByAddress(args.IP+":"+args.Port);
                            //0 1 2 3
                            for (int i = 0; i < session.Transports.Count; i++)
                            {
                                TransportInfo t = session.Transports[i];
                                //RTP
                                if (i%2 == 0&&t.Interleaved==channel)
                                {
                                    RTPPackage pack = RTPPackage.Parse(buffer);
                                    //响应RTP数据
                                    HandleMessageRTP(args.IP, args.Port, "TCP", channel, pack);
                                }
                                //RTCP
                                else if(i%2==1&&t.Interleaved==channel)
                                {

                                    //检查符合包，一个包中携带多个RTCP信息
                                    int offset2 = 0;
                                    while (offset2 < length)
                                    {
                                        byte[] buffer2 = new byte[length-offset2];
                                        Array.Copy(buffer, offset2, buffer2, 0, buffer2.Length);
                                        //TODO 
                                        AbsRTCPPackage pack = AbsRTCPPackage.Parse(buffer2);
                                        //响应RTP数据
                                        HandleMessageRTCP(args.IP, args.Port, "TCP", channel, pack);
                                        offset2 += pack.Length;
                                    }
                                }
                            }
                        }
                        catch(Exception ex)
                        {
                            int a = 1;
                        }
                        offset += 4 + length;
                    }
                    else
                    {
                        break;
                    }
                }
                //保留残余片断
                if (offset<args.Data.Length)
                {
                    byte[] fragment = new byte[args.Data.Length - offset];
                    Array.Copy(args.Data, offset, fragment, 0, fragment.Length);
                    args.State.Clear();
                    args.State.Data = fragment.ToList();
                }
                else
                {
                    args.State.Clear();
                }
                if (args.Socket.Available > 0|| !AutoCloseSession)
                {
                    if (args.Socket.Connected)
                    {
                        args.Socket.BeginReceive(args.State.Buffer, 0, args.State.Buffer.Length, SocketFlags.None, _sc.CallbackReceived, args.State);
                    }
                }
                else
                {
                    _sc.CloseSocket(args.Socket, 12);
                }
            }
        }
        /// <summary>
        /// 响应请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        protected override StatusCode HandleRequest(ref HttpContext context)
        {
            context.Response.Version =Version;
            //不添加默认的头信息
            context.Response.DontAddAutoHeader = true;

            context.Response.AddHeader(RTSPHeaderProperty.CSeq, context.Request.Headers.GetValue(RTSPHeaderProperty.CSeq));

            RequestMethod method = context.Request.Method;

            //SESSION
            var session = context.Request.GetHeaderValue(RTSPHeaderProperty.Session);

            if (!string.IsNullOrEmpty(session))
            {
                if (session.IndexOf(";") > 0)
                {
                    session = session.Substring(0, session.IndexOf(";"));
                }
                context.Response.AddHeader(RTSPHeaderProperty.Session, session);
            }

            try
            {
                if (method == RTSPMethod.OPTIONS)
                {
                    return HandleRequestOptions(ref context);
                }
                else if (method == RTSPMethod.SETUP)
                {
                    return HandleRequestSetup(ref context);
                }
                else if (method == RTSPMethod.DESCRIBE)
                {
                    return HandleRequestDescribe(ref context);
                }
                else if (method == RTSPMethod.PLAY)
                {
                    return HandleRequestPlay(ref context);
                }
                else if (method == RTSPMethod.PAUSE)
                {
                    return HandleRequestPause(ref context);
                }
                else if (method == RTSPMethod.TEARDOWN)
                {
                    return HandleRequestTeardown(ref context);
                }
                else if (method == RTSPMethod.SET_PARAMETER)
                {
                    return HandleRequestSetParameter(ref context);

                }//RTSP 1.0
                else if (method == RTSPMethod.ANNOUNCE)
                {
                    return HandlRequestAnnounce(ref context);

                }//RTSP 1.0
                else if (method == RTSPMethod.RECORD){
                    return HandleRequestRecord(ref context);
                }
                else if (method == RequestMethod.GET){

                }
                return RTSPStatus.NotAcceptable;
            }
            catch(Exception ex)
            {
                return RTSPStatus.InternalServerError;
            }
        }
        /// <summary>
        /// 响应Option请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StatusCode HandleRequestOptions(ref HttpContext context)
        {
            context.Response.AddHeader(RTSPHeaderProperty.Public, MethodPublic.Select(x => x.Name).ToArray());
            context.Response.AddHeader(RTSPHeaderProperty.Supported, string.Join(";", _features));
            // Send 200 OK
            return RTSPStatus.OK;
        }
        /// <summary>
        /// 响应Announce请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StatusCode HandlRequestAnnounce(ref HttpContext context)
        {
            SDPPackage sdp = SDPPackage.Parse(StringEncoder.Decode(context.Request.Body));
            RTSPUri uri = RTSPUri.Parse(context.Request.Path);
            MediaResource res= MediaLayer.Find(uri.Path);

            //开辟缓冲区
            if (res == null)
            {
                res = new MediaResource()
                {
                    //资源路径为媒体标识符号
                    ResourceName = uri.Path,
                    Description= sdp
                };
                foreach(var media in sdp.Medias)
                {
                    SDPAttribute[] controls = media.GetAttributes(SDPAttributeType.Control);
                    SDPAttribute[] rtmps = media.GetAttributes(SDPAttributeType.RtpMap);
                    if (controls!=null&&controls.Length > 0)
                    {
                        string control = (string)controls[0].Value;
                        MediaBuffer buffer = new MediaBuffer()
                        {
                            StreamId=control,
                        };

                        if (rtmps != null && rtmps.Length > 0)
                        {
                            SDPAttributeRTPMap rtmp = SDPAttributeRTPMap.Parse((string)rtmps[0].Value);
                            buffer.PayloadType = rtmp.PayloadType;
                            buffer.ClockRate = rtmp.ClockRate;
                            buffer.EncodingName = rtmp.EncodingName;
                        }

                        res.AddBuffer(buffer);
                    }
                }
                MediaLayer.Add(res);
            }

            return RTSPStatus.OK;
        }
        /// <summary>
        /// 响应RECORD请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StatusCode HandleRequestRecord(ref HttpContext context)
        {
            //仅能回应201/205 RTSP/1.0
            var sessionid = context.Request.GetHeaderValue(RTSPHeaderProperty.Session);
            var range = context.Request.GetHeaderValue(RTSPHeaderProperty.Range);
            var session = Sessions.Find(sessionid);
            session.ResourceName = RTSPUri.Parse(context.Request.Path).Path;
            session.IsPublisher = true;
            if (!RTSPTransportProtocol.IsTCP(session.TransferProtocol))
            {
                for (int i = 0; i < session.Transports.Count; i++)
                {
                    TransportInfo r = session.Transports[i];
                    if (i % 2 == 0)
                    {
                        RTPPackage rp = new RTPPackage();
                        rtp.SendMessage(session.Transports[0].ClientAddress, session.Transports[0].ClientPort, rp);
                    }
                    else
                    {
                        //RR 包
                        RTCPReceiverPackage rr = new RTCPReceiverPackage();

                        rtcp.SendMessage(session.Transports[1].ClientAddress, session.Transports[1].ClientPort, rr);
                    }
                }
            }
            return RTSPStatus.OK;
        }
        //TODO UDP模式下 audio和video一般分为两个会话进行传输，0号端口传输RTP数据包，1号端口传输RTCP数据包

        /// <summary>
        /// 响应Setup请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StatusCode HandleRequestSetup(ref HttpContext context)
        {
            var sessionid = context.Request.GetHeaderValue(RTSPHeaderProperty.Session);
            Session session = null;
            
            if (!string.IsNullOrEmpty(sessionid))
            {
                session = _sm.Find(sessionid);
            }
            else
            {
                session = new Session()
                {
                    Id = CacheControl.GenerateRandom(16),
                    Timeout = 0,
                    ClientAddress = context.ClientAddress + ":" + context.ClientPort,
                    MessageSendRTP = HandleMessageSendRTP,
                    MessageSendRTCP=HandleMessageSendRTCP
                };
                session.Pipe = context.Session;
                _sm.Add(session);
            }
            var transport = context.Request.Headers.GetValue(RTSPHeaderProperty.Transport);

            if (context.Request.Version == RTSPVersion.Version10)
            {
                //协商媒体类型
                //TCP类型与RTSP占用一个数据通道，仅提取interleaved
                RTSPTransportPropertyV1 transReq = RTSPTransportPropertyV1.Parse(transport);

                //测试发现多种客户端工具都不能协商传输模式，只能指定传输模式
                RTSPTransportPropertyV1 tranResp = new RTSPTransportPropertyV1
                {
                    Protocol = RTSPTransportProtocol.AVP,
                    DeliveryMode = "unicast",
                    ClientPort = transReq.ClientPort,
                };

                if (rtp!=null&&rtcp!=null&&rtp.Running && rtcp.Running)
                {
                    tranResp.ServerPort = $"{rtp.Port}-{rtcp.Port}";
                }

                if (RTSPTransportProtocol.IsTCP(transReq.Protocol))
                {
                    tranResp.Protocol = RTSPTransportProtocol.AVPTCP;
                }
                session.TransferProtocol = tranResp.Protocol;

                //TODO 资源路径解析有问题
                string ResourceName = RTSPUri.Parse(context.Request.Path).Path;

                //信道 RTP
                TransportInfo tiRTP = new TransportInfo();
                //信道 RTCP
                TransportInfo tiRTCP = new TransportInfo();
                //资源地址
                tiRTP.StreamId = ResourceName;
                tiRTCP.StreamId = ResourceName;
                tiRTP.ClientAddress = context.ClientAddress;
                tiRTCP.ClientAddress = context.ClientAddress;

                if (!string.IsNullOrEmpty(transReq.ClientPort))
                {
                    string[] ports = transReq.ClientPort.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                    tiRTP.ClientPort = int.Parse(ports[0]);
                    tiRTCP.ClientPort = int.Parse(ports[1]);
                }
                if (!string.IsNullOrEmpty(transReq.Interleaved))
                {
                    string[] inters = transReq.Interleaved.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                    tiRTP.Interleaved = int.Parse(inters[0]);
                    tiRTCP.Interleaved = int.Parse(inters[1]);
                    tranResp.ServerPort = null;
                    tranResp.Interleaved = transReq.Interleaved;
                }
                if (!session.Transports.Exists(x => x.StreamId == ResourceName))
                {
                    session.Transports.Add(tiRTP);
                    session.Transports.Add(tiRTCP);
                    //TODO 此处逻辑未确定
                    int rank=session.Transports.Count / 2-1;
                    MediaResource mb = MediaLayer.Query(tiRTP.StreamId);
                    mb.Buffers[rank].TransportChannel = tiRTP.ClientPort > 0 ? session.Transports.IndexOf(tiRTP) : tiRTP.Interleaved;
                }
                else
                {

                }
                context.Response.AddHeader(RTSPHeaderProperty.Transport, tranResp.ToString());
            }
            else
            {
                RTSPTransportProperty trans = RTSPTransportProperty.Parse(transport);
            }

            context.Response.AddHeader(RTSPHeaderProperty.Date, DateTime.Now.ToUniversalTime().ToString("r"));
            context.Response.AddHeader(RTSPHeaderProperty.AcceptRanges, "npt, clock, smpte");
            if (!context.Response.Headers.Contains(RTSPHeaderProperty.Session))
            {
                context.Response.AddHeader(RTSPHeaderProperty.Session, $"{session.Id}" + (session.Timeout > 0 ? $";timeout={session.Timeout}" : ""));
            }
            //context.Response.AddHeader(RTSPHeaderProperty.MediaProperties, "No-Seeking, Time-Progressing, Time-Duration=0.0");

            return RTSPStatus.OK;

        }
        /// <summary>
        /// 响应Describe请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StatusCode HandleRequestDescribe(ref HttpContext context)
        {
            context.Response.AddHeader(RTSPHeaderProperty.ContentBase, context.Request.Path);
            context.Response.AddHeader(RTSPHeaderProperty.ContentType, "application/sdp");
            var sessionid = context.Request.GetHeaderValue(RTSPHeaderProperty.Session);
            var session = Sessions.Find(sessionid);
            //SDPPackage sdp = new SDPPackage();
            //sdp.Session = new SDPSessionDescription();
            //SDPSessionDescription session = sdp.Session;
            //session.Version = 1;
            //session.Origin = new SDPOrigin()
            //{
            //    UserName="mozi",
            //    SessionId=1,
            //    SessionVersion=1,
            //    AddressType="IP4",
            //    Address="127.0.0.1"
            //};
            //session.SessionName = "mozi.livecast";
            //session.Connection = new SDPConnection()
            //{
            //    Address = "127.0.0.1",
            //    TTL = 32,
            //    PortCount=2
            //};
            //session.BandWidths = new System.Collections.Generic.List<SDPBandWidth>() { { new SDPBandWidth() { BandWidth=10*1024} } };

            //SDPMediaDescription video = new SDPMediaDescription();
            //video.Media = new SDPMedia()
            //{
            //    MediaType = SDPMediaType.Video,
            //    Port = 3005,
            //    PortCount = 0,
            //    Protocol = RTSPTransportProtocol.AVP,
            //    FormatType = new System.Collections.Generic.List<int> { 31 }
            //};
            //video.MediaTitle = "stream";
            //sdp.AddMedia(video);
            //SDPMediaDescription audio = new SDPMediaDescription();
            //sdp.AddMedia(audio);


            //提取描述文档
            RTSPUri uri = RTSPUri.Parse(context.Request.Path);
            MediaResource buffer=MediaLayer.Find(uri.Path);
            if (session != null)
            {
                session.ResourceName = uri.Path;
            }
            if (buffer != null&&buffer.Description!=null)
            {
                context.Response.Write(buffer.Description.ToString());
                context.Response.AddHeader(RTSPHeaderProperty.ContentLength, context.Response.Body.Length.ToString());
                return RTSPStatus.OK;
            }
            else
            {
                return RTSPStatus.NotFound;
            }
        }
        /// <summary>
        /// 响应Play请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StatusCode HandleRequestPlay(ref HttpContext context)
        {
            var range = context.Request.GetHeaderValue(RTSPHeaderProperty.Range);
            var sessionid = context.Request.GetHeaderValue(RTSPHeaderProperty.Session);
            context.Response.AddHeader(RTSPHeaderProperty.SeekStyle, "Next");
            context.Response.AddHeader(RTSPHeaderProperty.Date, DateTime.Now.ToUniversalTime().ToString("r"));
            var session = Sessions.Find(sessionid);
            _sm.SetSessionState(sessionid, SessionState.Play);
            if (!RTSPTransportProtocol.IsTCP(session.TransferProtocol))
            {
                for (int i = 0; i < session.Transports.Count; i++)
                {
                    TransportInfo r = session.Transports[i];
                    if (i % 2 == 0)
                    {
                        RTPPackage rp = new RTPPackage();
                        rtp.SendMessage(session.Transports[0].ClientAddress, session.Transports[0].ClientPort, rp);
                    }
                    else
                    {
                        //RR 包
                        //RTCPSenderPackage rr = new RTCPSenderPackage();
                        //rr.SendTime = DateTime.UtcNow;
                        //rr.Identifier = MediaLayer.First().Packages[0].SSRC;
                        //rtcp.SendMessage(session.Transports[1].ClientAddress, session.Transports[1].ClientPort, rr);
                    }
                }
            }
            RTSPUri uri = RTSPUri.Parse(context.Request.Path);
            
            session.ResourceName = uri.Path;
            //确定资源
            var resource = MediaLayer.Find(uri.Path);
            var publisher = _sm.FindPublisher(uri.Path);
            //if (RTSPTransportProtocol.IsTCP(session.TransferProtocol))
            //{
                session.Play();
                //foreach (var s in _sm.GetSubscribers())
                //{
                //    s.Play();
                //    //foreach (var p in resource.Buffers)
                //    //{
                //    //    //先发送SR 
                //    //    RTCPSenderPackage rr = new RTCPSenderPackage();
                //    //    rr.SendTime = DateTime.UtcNow;
                //    //    rr.Identifier = p.Packages[0].SSRC;
                //    //    rr.PacketCount = (uint)p.Packages.Count(x => x != null);
                //    //    //rr.PayloadLength=p.Packages.Where(x => x!=null).Sum(x=>x)
                //    //    session.Pipe.Send(PackMixedRTP((byte)(p.TransportChannel+1), rr.Pack()));

                //    //    foreach (var mc in p.Packages)
                //    //    {
                //    //        if (mc != null)
                //    //        {
                //    //            session.Pipe.Send(PackMixedRTP((byte)p.TransportChannel, mc.Pack()));
                //    //        }
                //    //    }
                //    //}
                //}
            //}
            //else
            //{
            //    //foreach (var se in _sm.GetSubscribers())
            //    //{
            //    //    foreach (var p in buffer.Packages)
            //    //    {
            //    //        rtp.SendMessage(se.ClientAddress,, p);
            //    //    }
            //    //}
            //}
            return RTSPStatus.OK;
        }
        /// <summary>
        /// 响应Pause请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StatusCode HandleRequestPause(ref HttpContext context)
        {
            var sessionid = context.Request.GetHeaderValue(RTSPHeaderProperty.Session);
            _sm.SetSessionState(sessionid, SessionState.Pause);
            return RTSPStatus.NotAcceptable;
        }
        /// <summary>
        /// 响应Teardown请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StatusCode HandleRequestTeardown(ref HttpContext context)
        {
            var sessionid = context.Request.GetHeaderValue(RTSPHeaderProperty.Session);
            _sm.SetSessionState(sessionid, SessionState.Close);
            _sm.Remove(sessionid);
            //对于持久链接，此值用以关闭会话
            context.CloseSession=true;
            return RTSPStatus.OK;
        }
        /// <summary>
        /// 响应SetParameter请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StatusCode HandleRequestSetParameter(ref HttpContext context)
        {
            return RTSPStatus.NotAcceptable;
        }
        /// <summary>
        /// GetParameter请求 S->C
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private StatusCode GetParameter(ref HttpContext context)
        {
            return RTSPStatus.NotAcceptable;
        }
        public void PlayNotify(string url, RequestComplete callback)
        {

        }
        /// <summary>
        /// 服务器向客户机发送重定位请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="callback"></param>
        public void Redirect(string url, RequestComplete callback)
        {

        }
        /// <summary>
        /// 发布媒体
        /// </summary>
        /// <param name="path"></param>
        public void PublishMedia(string path)
        {

        }
    }
}
